package cn.com.czpb.client.module.news.adapter;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.annotation.StyleRes;
import android.text.Selection;
import android.text.Spannable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import cn.com.czpb.client.R;
import cn.com.czpb.client.api.InterfaceJsonfile;
import cn.com.czpb.client.model.news.ComResultBean;
import cn.com.czpb.client.model.news.ComResultEntity;
import cn.com.czpb.client.model.news.CommBean;
import cn.com.czpb.client.module.news.activity.CommentActivity;
import cn.com.czpb.client.net.Factory;
import cn.com.czpb.client.utils.DeviceUtils;
import cn.com.czpb.client.utils.LogUtils;
import cn.com.czpb.client.utils.PageCtrl;
import cn.com.czpb.client.utils.ParamUtils;
import cn.com.czpb.client.utils.SPUtil;
import cn.com.czpb.client.utils.TUtils;
import cn.com.czpb.client.utils.TextUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/8/14.
 */

public class NewsCommentRvAdapter extends BaseMultiItemQuickAdapter<CommBean.ChildrenEntity,BaseViewHolder> {
    private String nid;
    private String cid;
    private SPUtil spu;
    private String type;
    private Context context;
    private int position;
    private int parent_position;
    /**
     * Same as QuickAdapter#QuickAdapter(Context,int) but with
     * some initialization data.
     *
     * @param data A new list is created out of this one to avoid mutable list
     */
    public NewsCommentRvAdapter(List<CommBean.ChildrenEntity> data,String nid,String type,Context context,int parent_position) {
        super(data);
        spu=SPUtil.getInstance();
        this.nid=nid;
        this.type=type;
        this.context=context;
        this.parent_position=parent_position;

        addItemType(0, R.layout.item_comm_recycler);
    }

    @Override
    protected void convert(final BaseViewHolder helper, final CommBean.ChildrenEntity item) {
        if (item.getMediatype().equals("1")){
            helper.getView(R.id.vip).setVisibility(View.VISIBLE);
        }

        switch (helper.getItemViewType()){
            case 0:
                position=helper.getLayoutPosition();
                helper.setText(R.id.num_com,helper.getLayoutPosition()+1+"");
                helper.setText(R.id.tv_name_comm_recycler, TextUtils.getLengthText(item.getNickname(),8));
                helper.setText(R.id.tv_dianzan_comm,item.getPraise());
                helper.setText(R.id.tv_lv_comm_recycler,item.getUlevel()+" ");
                final ImageView iv_Praise = helper.getView(R.id.iv_dianzan);
                final TextView tv_Praise = helper.getView(R.id.tv_dianzan_comm);
                if (item.getIspraise().equals("0")) {
                    tv_Praise.setTextColor(context.getResources().getColor(R.color.color_999999));
                    iv_Praise.setImageResource(R.drawable.dianzan);
                } else {
                    tv_Praise.setTextColor(context.getResources().getColor(R.color.color_df3031));
                    iv_Praise.setImageResource(R.drawable.dianzan_selected);
                }

                if (item.getReplyto().getContent()!=null){
                    helper.setText(R.id.tv_content_comm_recycler,item.getContent()+" /回复/ "+item.getReplyto().getNickname()+" : "+item.getReplyto().getContent());
                }else {
                    helper.setText(R.id.tv_content_comm_recycler,item.getContent());
                }
                helper.setText(R.id.tv_time_comm_recycler,item.getDateline());
                helper.addOnClickListener(R.id.tv_content_comm_recycler);
                helper.getView(R.id.tv_content_comm_recycler).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        Intent intent = new Intent();
                        intent.putExtra("cid", item.getCid());
                        intent.putExtra("username", item.getNickname());
                        intent.setAction(CommentActivity.SEND_MSG);
                        mContext.sendBroadcast(intent);
                    }
                });
                helper.getView(R.id.ll_dianzan).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Priase(item.getCid(),tv_Praise,iv_Praise);
                    }
                });
//                helper.getView(R.id.ll_user).setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View view) {
//                        Intent intent = new Intent();
//                        if ("1".equals(item.getMediatype())) {
//                            intent.putExtra("focusUid", item.getUid());
//                            intent.setClass(context, SubscribeDetailActivity.class);
//                        }else {
//                            intent.putExtra("uid", item.getUid());
//                            intent.setClass(context, PersonPageActivity.class);
//                        }
//                        mContext.startActivity(intent);
//                        AAnim.ActivityStartAnimation((Activity) context);
//                    }
//                });
//                helper.getView(R.id.tv_lv_comm_recycler).setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View view) {
//                        Intent intent=new Intent(context, LevelActivity.class);
//                        intent.putExtra("uid",item.getUid());
//                        mContext.startActivity(intent);
//                        AAnim.ActivityStartAnimation((Activity) context);
//                    }
//                });
//                helper.getView(R.id.tv_content_comm_recycler).setOnLongClickListener(new View.OnLongClickListener() {
//                    @Override
//                    public boolean onLongClick(View view) {
//                        TextView tv=helper.getView(R.id.tv_content_comm_recycler);
//                        tv.setBackgroundColor(mContext.getResources().getColor(R.color.color_d4d4d4));
//                        String msg=tv.getText().toString();
//                        CommPop cp=new CommPop((Activity) context,msg,tv,1);
//                        cp.showAsPullUp(tv,0,0);
//
//                        return true;
//                    }
//
//                });
                break;
        }
    }
    class ReplyDialog extends Dialog implements View.OnClickListener {
        EditText et_reply;
        TextView tv_send;
        CommBean.ChildrenEntity item;
        public ReplyDialog(Context context) {
            super(context);
            init();
        }

        public ReplyDialog(@NonNull Context context, @StyleRes int themeResId ,CommBean.ChildrenEntity item) {
            super(context, themeResId);
            this.item=item;
            init();

        }

        private void init() {
            WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
            int width = wm.getDefaultDisplay().getWidth();
            View view = LayoutInflater.from(mContext).inflate(R.layout.et_reply_laout, null);
            setContentView(view);
            et_reply = view.findViewById(R.id.et_reply);
            tv_send = view.findViewById(R.id.tv_send);
            tv_send.setOnClickListener(this);
            et_reply.setText("回复 "+item.getNickname()+"：");

            Window dialogWindow = getWindow();
            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
            dialogWindow.setGravity(Gravity.END | Gravity.BOTTOM);
            lp.width = width;
            dialogWindow.setAttributes(lp);
        }

        @Override
        public void onClick(View view) {

            CharSequence msg1 = et_reply.getText().toString().trim();
            if (msg1 instanceof Spannable){
                Spannable spanText = (Spannable)msg1;
                Selection.setSelection(spanText, msg1.length());
            }
            String msg = et_reply.getText().toString().trim();
            et_reply.setSelection(msg.length());
            if (spu.getUser() == null) {
                PageCtrl.start2LoginActivity((Activity) mContext);
            } else {
                if (msg == null) {
                    TUtils.toast("请输入内容");
                } else {
                    LogUtils.e("msg--"+msg+item.getCid());
                    sendComment(msg,item.getCid());
                }
            }
        }

        private void sendComment(String content, String cid) {

            Map<String, String> map = new HashMap<>();
            map.put("nid", nid);
            map.put("title", nid);
            map.put("uid", spu.getUser().getUid());
            map.put("type", type);
            map.put("content", content);
            map.put("cid", cid);
            map.put("json_url", "fsdfsdfsfs");//随便传一个
            map.put("siteid", InterfaceJsonfile.SITEID);
            Factory.provideHttpService()
                    .newsComment(ParamUtils.getRequestParam(map))
                    .onBackpressureBuffer()
                    .subscribeOn(Schedulers.io())
                    .filter(new Func1<ComResultEntity, Boolean>() {
                        @Override
                        public Boolean call(ComResultEntity entity) {
                            LogUtils.i("200-->" + entity.code);
                            if ("200".equals(entity.code)) {
                                LogUtils.i("200-->成功");
                                return true;
                            }
                            LogUtils.i("200失败");
                            return false;
                        }
                    })
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Action1<ComResultEntity>() {
                        @Override
                        public void call(ComResultEntity entity) {

                            if ("200".equals(entity.code)) {
                                TUtils.toast("评论成功");
                                et_reply.setText("");
                            } else {
                                TUtils.toast(entity.msg);
                            }
//                            setData();
                        }
                    }, new Action1<Throwable>() {
                        @Override
                        public void call(Throwable throwable) {
                            TUtils.toast("评论失败");

                        }
                    });
        }

    }
    public void Priase(final String cid, final TextView tv, final ImageView iv){
        final ComResultBean[] obj = {new ComResultBean()};
        Map<String,String> map=new HashMap<>();
        map.put("uid",spu.getUser().getUid());
        map.put("device", DeviceUtils.getMyUUID(mContext));
        map.put("cid",cid);
        map.put("siteid", InterfaceJsonfile.SITEID);

        Factory.provideHttpService().PraiseOnComment(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<ComResultEntity, Boolean>() {
                    @Override
                    public Boolean call(ComResultEntity emptyEntity) {
                        return true;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<ComResultEntity>() {
                    @Override
                    public void call(ComResultEntity emptyEntity) {

                        LogUtils.e("code---"+emptyEntity.code);
                        if (emptyEntity.code.equals("200")){
                            tv.setText(emptyEntity.data.getPraisenum());
                            tv.setTextColor(mContext.getResources().getColor(R.color.color_df3031));
                            iv.setImageResource(R.drawable.dianzan_selected);
                            Intent intent = new Intent();
                            intent.putExtra("position", position);
                            intent.putExtra("f_position", parent_position);
                            intent.setAction(CommentActivity.PRASE);
                            mContext.sendBroadcast(intent);
                        }else {
                            TUtils.toast(emptyEntity.msg);
                        }
                    }
                });

    }
}
